package com.xiuyi.pixsynergybackend.service.user;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiuyi.pixsynergybackend.constant.UserConstant;
import com.xiuyi.pixsynergybackend.controller.user.vo.*;
import com.xiuyi.pixsynergybackend.dal.dataobject.enums.UserRoleEnum;
import com.xiuyi.pixsynergybackend.dal.dataobject.user.UserDO;
import com.xiuyi.pixsynergybackend.dal.mapper.user.UserMapper;
import com.xiuyi.pixsynergybackend.exception.BusinessException;
import com.xiuyi.pixsynergybackend.exception.ErrorCode;
import com.xiuyi.pixsynergybackend.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zyt
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-05-02 17:50:44
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO>
        implements UserService {

    /**
     * 用户注册
     *
     * @param userRegisterReqVO
     * @return
     */
    @Override
    public long userRegister(UserRegisterReqVO userRegisterReqVO) {
        // 1、校验参数
        if (StrUtil.hasBlank(userRegisterReqVO.getUserAccount(), userRegisterReqVO.getUserPassword(), userRegisterReqVO.getCheckPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userRegisterReqVO.getUserAccount().length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userRegisterReqVO.getUserPassword().length() < 8 || userRegisterReqVO.getCheckPassword().length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userRegisterReqVO.getUserPassword().equals(userRegisterReqVO.getCheckPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        // 2、检查用户账号是否和数据库中已有的重复
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userRegisterReqVO.getUserAccount());
        long count = this.baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 3、密码一定需要加密
        String encryptPassword = getEncryptPassword(userRegisterReqVO.getUserPassword());
        // 4、插入数据库中
        UserDO userDO = new UserDO();
        userDO.setUserAccount(userRegisterReqVO.getUserAccount());
        userDO.setUserPassword(DigestUtil.md5Hex(encryptPassword));
        userDO.setUserName("默认用户");
        userDO.setUserRole(UserRoleEnum.USER.getValue());
        boolean saveResult = this.save(userDO);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，请咨询管理员");
        }
        return userDO.getId();
    }

    /**
     * 用户登录
     *
     * @param userLoginReqVO
     * @param request
     * @return
     */
    @Override
    public UserLoginRespVO userLogin(UserLoginReqVO userLoginReqVO, HttpServletRequest request) {
        // 1、校验用户
        if (StrUtil.hasBlank(userLoginReqVO.getUserAccount(), userLoginReqVO.getUserPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userLoginReqVO.getUserAccount().length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号错误");
        }
        if (userLoginReqVO.getUserPassword().length() < 8 ) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码错误");
        }
        // 2、对用户传递的密码进行加密
        String encryptPassword = getEncryptPassword(userLoginReqVO.getUserPassword());
        // 3、查询数据库中的用户是否存在
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userLoginReqVO.getUserAccount());
        queryWrapper.eq("userPassword", DigestUtil.md5Hex(encryptPassword));
        UserDO userDO = this.baseMapper.selectOne(queryWrapper);
        // 不存在，跑异常
        if (userDO == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或者密码错误");
        }
        // 保存用户的登录状态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, userDO);
        return this.getLoginUserVO(userDO);
    }

    /**
     * 获取加密后的密码
     *
     * @param userPassword
     * @return
     */
    @Override
    public String getEncryptPassword(String userPassword) {
        // 加盐，混淆密码
        final String SALT = "xiuyi";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    /**
     * 获取脱敏的已登录用户的信息（DO与VO之间的转换）
     *
     * @param userDO
     * @return
     */
    @Override
    public UserLoginRespVO getLoginUserVO(UserDO userDO) {
        if (userDO == null) {
            return null;
        }
        UserLoginRespVO userLoginRespVO = new UserLoginRespVO();
        BeanUtil.copyProperties(userDO, userLoginRespVO);
        return userLoginRespVO;
    }

    /**
     * 获取当前已登录的用户（用于Session会话传递）
     *
     * @param request
     * @return
     */
    @Override
    public UserDO getLoginUser(HttpServletRequest request) {
        // 判断当前是否有登录的用户
        Object userObject = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        UserDO currentUser = (UserDO) userObject;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库中继续查询（前者的代码是通过缓存的形式）
        Long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 判断当前是否有登录的用户
        Object userObject = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (userObject == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    /**
     * 获取脱敏的用户的信息（DO与VO之间的转换）
     *
     * @param userDO
     * @return
     */
    @Override
    public UserVO getUserVO(UserDO userDO) {
        if (userDO == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(userDO, userVO);
        return userVO;
    }

    /**
     * 获取脱敏的用户信息的列表（DO与VO之间的转换）
     *
     * @param userDOList
     * @return
     */
    @Override
    public List<UserVO> getUserVOList(List<UserDO> userDOList) {
        if (CollUtil.isEmpty(userDOList)) {
            return new ArrayList<>();
        }
        return userDOList.stream()
                .map(this::getUserVO)
                .collect(Collectors.toList());
    }

    /**
     * 获取查询条件
     *
     * @param userQueryReqVO
     * @return
     */
    @Override
    public QueryWrapper<UserDO> getQueryWrapper(UserQueryReqVO userQueryReqVO) {
        ThrowUtils.throwIf(userQueryReqVO == null, ErrorCode.PARAMS_ERROR, "请求参数为空");
        Long id = userQueryReqVO.getId();
        String userName = userQueryReqVO.getUserName();
        String userAccount = userQueryReqVO.getUserAccount();
        String userProfile = userQueryReqVO.getUserProfile();
        String userRole = userQueryReqVO.getUserRole();
        String sortField = userQueryReqVO.getSortField();
        String sortOrder = userQueryReqVO.getSortOrder();
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 是否为管理员
     *
     * @param userDO
     * @return
     */
    @Override
    public boolean isAdmin(UserDO userDO) {
        return userDO != null && !UserRoleEnum.ADMIN.getValue().equals(userDO.getUserRole());
    }
}




